﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Web;

namespace CookingBg.Services
{
    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class UserService
    {
        [WebInvoke(Method = "POST", UriTemplate = "RegisterUser", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)]
        public string RegisterUser(string userName, string passwordHash, string email)
        {
            var model = new Entities();
            var userOld = model.Users.FirstOrDefault(u => u.UserName.ToUpper() == userName.ToUpper());
            if (userOld != null)
            {
                return "The username you picked is already being used";
            }
            User user = new User();
            user.UserName = userName;
            user.PasswordHash = passwordHash;
            user.Email = email;
            model.AddToUsers(user);
            model.SaveChanges();
            return "";
        }

        [WebInvoke(Method = "POST", UriTemplate = "ChangePassword", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json)]
        public void ChangePassword(long userId, string passwordHash)
        {
            var model = new Entities();
            var userOld = model.Users.Single(u => u.ID == userId);
            userOld.PasswordHash = passwordHash;
            model.SaveChanges();
        }

        [WebInvoke(Method = "POST", UriTemplate = "LogIn", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        public long LogIn(string userName, string passwordHash)
        {
            var model = new Entities();
            var user = model.Users.SingleOrDefault(u => u.UserName.ToUpper() == userName.ToUpper() && u.PasswordHash.ToUpper() == passwordHash.ToUpper());
            if (user == null)
                return -1;
            return user.ID;
        }
    }
}